//
//  OPMLViewController.m
//  RssReader
//
//  Created by 旺财 on 10-10-31.
//  Copyright (c) 2010年 __MyCompanyName__. All rights reserved.
//

#import "OPMLViewController.h"
#import "RssReadViewController.h"
#import "RssDetailViewController.h"
#import "RssFeed.h"
#import "Cell1.h"
#import "Cell2.h"
#import "TableHeadController.h";
@implementation OPMLViewController


#pragma mark -
#pragma mark View lifecycle
@synthesize list;
@synthesize url;
@synthesize vType;//1:opml;2:rss;
@synthesize md5filename;
@synthesize rssurl;
@synthesize isback;
@synthesize notreadcount;
@synthesize currow;
@synthesize wcCount;
@synthesize myLoveCount;



-(void) setrootNode: (GDataXMLElement *)root
{
	//[rootNode release];
	rootNode=[root copy];
}

-(GDataXMLElement *)getrootNode
{
	return rootNode;
}

//获取旺财推荐
-(NSString *)GetRecommended
{
	if ([[Common getConfig] canRecommended])
	{
		if ([[Common getConfig].recommendedVer isEqualToString:[Common getConfig].recommendedLocalVer] && [Common getConfig].recommendedVer!=nil)
			return nil;
		NSError *error;
		NSString *con= [NSString stringWithContentsOfURL:[NSURL URLWithString:[Common getConfig].recommendedURL] encoding:NSUTF8StringEncoding  error:&error];
		if (con==nil)
		{
			return @"-1";
		}
		else
		{
			[[Common getConfig].recommendedVer writeToFile: [Common getConfig].recommendedLocalVerFilePath atomically:YES encoding:NSUTF8StringEncoding error:nil];
			return con;
		}
	}
	else {
		if ([[NSFileManager defaultManager]
			 fileExistsAtPath:[Common getConfig].recommendedLocalVerFilePath] )
			[[NSFileManager defaultManager] removeItemAtPath:[Common getConfig].recommendedLocalVerFilePath error:nil];
		return @"";
	}

}
-(void) restoreSelf
{
	
	if ([Common getConfig].restore) {
		[[NSFileManager defaultManager] removeItemAtPath:[Common getConfig].rootOPMLFileFullPath error:nil];
		[[NSFileManager defaultManager] removeItemAtPath:[Common getConfig].cacheFullDir error:nil];
		[[NSFileManager defaultManager] removeItemAtPath:[Common getConfig].recommendedLocalVerFilePath error:nil];
		NSUserDefaults *defaults=[NSUserDefaults standardUserDefaults];
		[defaults setValue:[NSNumber numberWithBool: NO] forKey:@"Restore"];
		[defaults setValue:[NSNumber numberWithBool: YES] forKey:@"defaultOpen"];
		[defaults setValue:[NSNumber numberWithBool: YES] forKey:@"wctj"];
		[defaults setValue:[NSNumber numberWithInteger:30] forKey:@"updateRSS"];
		[Common initConfig];

	}
}

//初始化
-(void) initFirst
{	
	[Common initConfig];
	//还原
	[self restoreSelf];
	//初始化cache目录
	[Common initDir:[[Common getConfig] cacheFullDir]];
	//初始化oplm文件
	[Common initOPMLby:[[Common getConfig] resourceOMPLfielpath] to:[[Common getConfig] rootOPMLFileFullPath]];
	//获取旺财推荐
	NSString *recommendedContent=[self GetRecommended];
	//获取根节点
	OMPLFeed *opf=[[OMPLFeed alloc] init];
	[self setrootNode:[opf getRootNodeFrom:[[Common getConfig] rootOPMLFileFullPath] islocal:YES recommended:recommendedContent]];
	self.wcCount=opf.wcCount;
	self.myLoveCount=opf.myLoveCount;
	//czzz
	[opf release];
	self.title=@"旺财阅读";
	self.vType=1;
	self.url=@"//opml/body/outline";
	//初始化左边按钮
	UIBarButtonItem *addButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:nil];
    self.navigationItem.leftBarButtonItem = addButton;
	[addButton release];
	return;
}

-(NSMutableDictionary *) initRssList:(OPMLViewController *)controller isforce:(BOOL)force
{
	RssFeed *rf=[[RssFeed alloc] init];
	[rf parseXMLFileAtURL:controller.rssurl cachefile:controller.md5filename isforce:force updateRss:[Common getConfig].updateRSSTime];
	
	//NSLog(@"stories beforre retain:%d", [controller.list retainCount]);
	
	
	//NSData *buffer = [NSKeyedArchiver archivedDataWithRootObject: [rf stories]];
	//[controller setList:[[NSMutableArray alloc]  initWithArray:[rf stories] copyItems:YES]];
	//controller.list = [NSKeyedUnarchiver unarchiveObjectWithData: buffer];
	//[buffer release];
//	NSLog(@"controller after retain:%d", [controller.list retainCount]);

//	NSLog(@"stories beforre retain:%d", [rf retainCount]);
	
	controller.list=[[NSMutableArray alloc] initWithArray:[rf stories] copyItems:YES];
	
	NSLog(@"controller after retain:%d", [rf  retainCount]);
	
	//[buffer release];
	//controller.list
	OMPLFeed *opf=[[OMPLFeed alloc] init];
	controller.notreadcount=rf.notreadcount;
	[controller setrootNode: [opf WriteNotReadRssCount: controller.notreadcount root:rootNode byXpath:controller.url lastupdate:rf.lastUpdateState ]];
	[Common setroot:rootNode];
	NSMutableDictionary * dic=[[NSMutableDictionary alloc] init];
	[dic setValue:[NSNumber numberWithInteger:rf.lastUpdateState] forKey:@"lastupdate"];
	
	[dic setValue:[NSNumber numberWithInteger: rf.notreadcount] forKey:@"count"];
	NSLog(@"%d", controller.notreadcount);
	NSLog(@"controller after retain:%d", [rf  retainCount]);
	
	[opf release];	
	//[rf release];
	//NSLog(@"%d", controller.notreadcount);
	return dic;	
}




// 从网络获取rss 或者 ompl by zz 
- (void) getOpmlOrRss:(BOOL)force
{
	//opml节点
	if (vType==1)
	{	OMPLFeed *opf=[[OMPLFeed alloc] init];
		[self.list removeAllObjects];
		self.list = [[NSMutableArray alloc] initWithArray:[opf getCurArrFrom:rootNode usexpath:url] copyItems:YES];
		[opf release];
	}
	//rss节点
	else if (vType==2)
	{
		[self initRssList:self isforce:force];
	}
	
}
//导航右边按钮刷新和载入转换
-(void)showLoading:(BOOL )show {
	// initing the loading view
	if (show)
	{
		CGRect frame = CGRectMake(0.0, 0.0, 30.0, 25.0);
		UIActivityIndicatorView *loading = [[UIActivityIndicatorView alloc] initWithFrame:frame];
		[loading startAnimating];
		[loading sizeToFit];
		loading.autoresizingMask = (UIViewAutoresizingFlexibleLeftMargin |
								UIViewAutoresizingFlexibleRightMargin |
								UIViewAutoresizingFlexibleTopMargin |
								UIViewAutoresizingFlexibleBottomMargin);
		UIBarButtonItem *loadingView = [[UIBarButtonItem alloc] initWithCustomView:loading];
		//[loading release];
		//loadingView.target = self;
		self.navigationItem.rightBarButtonItem = loadingView;
		
		[loadingView release];
		[loading release];
	}
	else 
	{
		UIBarButtonItem *refButton = [[UIBarButtonItem alloc] 
									   initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh
									   target:self action:@selector(refresh:)];
		self.navigationItem.rightBarButtonItem = refButton;
		[refButton release];
	}

}

//更新节点界面变化
-(void) updateUI:(NSMutableDictionary *) dic
{
	NSInteger row=[[dic valueForKey:@"row"] integerValue];
	NSInteger section=[[dic valueForKey:@"section"] integerValue];
	BOOL isstar=[[dic valueForKey:@"isstar"] boolValue];
	NSIndexPath *indexPath = [NSIndexPath indexPathForRow:row inSection:section];
	Cell1 *cell =(Cell1 *)[self.tableView cellForRowAtIndexPath:indexPath];
	if (isstar)
	{
		//[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
		//UIView *subView =[cell viewWithTag:13];
		if (cell.button.hidden)
		{
			[cell setAccessoryType:(UITableViewCellAccessoryNone)];
		}
		else 
		{
			[cell.button setHidden:YES];
			
		}

		//[cell.typeimage setHidden:YES];
		if ([dic objectForKey:@"color"]!=nil)
		{
			[cell.active setActivityIndicatorViewStyle:UIActivityIndicatorViewStyleWhite];
		}
		else 
		{
			[cell.active setActivityIndicatorViewStyle:UIActivityIndicatorViewStyleGray];
			self.navigationItem.rightBarButtonItem.enabled=NO;
		}
		cell.active.hidden=NO;
	}
	else 
	{
		//[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
		NSInteger count=[[dic valueForKey:@"count"] intValue];
		NSInteger lastupdate=[[dic valueForKey:@"lastupdate"] intValue];
		if (lastupdate==-1 )
		{
			[cell setSelected:NO];
		}

		
		
		//UIImage *c =[UIImage imageNamed:@"ball.png"];
		//UIImageView *x=[[UIImageView alloc] initWithImage:c];
		//[cell setAccessoryView:x];
		//[cell.typeimage setHidden:NO];
		cell.active.hidden=YES;
		NSString *type=[dic objectForKey:@"type"];
		if ([type isEqualToString:@"rss"]) 
		{
			cell.button.hidden=NO;
			if (lastupdate==1 || lastupdate==0)
			{
				if (lastupdate==1)
				{
						cell.imageView.image =[UIImage imageNamed:@"leftall.png"];
				}
				if (count==0) 
				{
					[cell.countlabel setText:@"-"];
				}
				else
				{
					[cell.countlabel setText:[NSString stringWithFormat: @"%d",count]];
				}
			}
			else if (lastupdate==-1)
			{
				cell.imageView.image =[UIImage imageNamed:@"lefered.png"];	
			}
		}
		else 
		{
			[cell setAccessoryType:(UITableViewCellAccessoryDisclosureIndicator)];
			
			if (count==0) 
			{
				[cell.countlabel setText:@"-"];
			}
			else
			{
				[cell.countlabel setText:[NSString stringWithFormat: @"%d",count]];
			}
		}
	}
	//[dic release];
	//[cell release];
	return;
}

//新线程后台刷新数据
- (void)backrefresh 
{	
	NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
	NSMutableDictionary * item;
	NSInteger tmpcount;
	NSString *tmpurl;
	NSString *tmpmd5filename;
	NSString *tmprssurl;
	NSMutableDictionary *dic;
	
	for(NSInteger row=0;row<[self.list count];row++)
	{
		//tmpurl=[[NSString alloc] init];
		dic=[[NSMutableDictionary alloc] init];		
		item=[[NSMutableDictionary alloc] initWithDictionary:[self.list objectAtIndex:row]];
		NSString *tmpvt=[item objectForKey:@"vtype"];
		if ([tmpvt isEqualToString:@"opml"]) 
		{
			if (self.wcCount!=0 && self.myLoveCount!=0)
			{
				if (row>=self.wcCount+self.myLoveCount)
				{
					[dic setValue:[NSNumber numberWithInteger: row-self.wcCount-self.myLoveCount] forKey:@"row"];
					[dic setValue:[NSNumber numberWithInteger: 2] forKey:@"section"];
				}
				else if (row>=self.myLoveCount && row<self.wcCount+self.myLoveCount) 
				{
					[dic setValue:[NSNumber numberWithInteger: row-self.myLoveCount] forKey:@"row"];
					[dic setValue:[NSNumber numberWithInteger: 1] forKey:@"section"];
				}
				else 
				{
					[dic setValue:[NSNumber numberWithInteger: row] forKey:@"row"];
					[dic setValue:[NSNumber numberWithInteger: 0] forKey:@"section"];	
				}
				
			}
			else if (self.wcCount==0 && self.myLoveCount==0)
			{	
				[dic setValue:[NSNumber numberWithInteger: row] forKey:@"row"];
				[dic setValue:[NSNumber numberWithInteger: 0] forKey:@"section"];
			
			}
			else  if (self.wcCount==0 && self.myLoveCount!=0)
			{
				if (row>=self.myLoveCount)
				{
					[dic setValue:[NSNumber numberWithInteger: row-self.myLoveCount] forKey:@"row"];
					[dic setValue:[NSNumber numberWithInteger: 1] forKey:@"section"];
				}
				else {
					[dic setValue:[NSNumber numberWithInteger: row] forKey:@"row"];
					[dic setValue:[NSNumber numberWithInteger: 0] forKey:@"section"];
				}
			}
			else if (self.wcCount!=0 && self.myLoveCount==0)
			{
				if (row>=self.wcCount)
				{
					[dic setValue:[NSNumber numberWithInteger: row-self.wcCount] forKey:@"row"];
					[dic setValue:[NSNumber numberWithInteger: 1] forKey:@"section"];
				}
				else {
					[dic setValue:[NSNumber numberWithInteger: row] forKey:@"row"];
					[dic setValue:[NSNumber numberWithInteger: 0] forKey:@"section"];
				}
				
			}

			/*
			if ([self.tableView numberOfSections]>1)
			{
				if (row>=self.wcCount)
				{
					[dic setValue:[NSNumber numberWithInteger: row-self.wcCount] forKey:@"row"];
					[dic setValue:[NSNumber numberWithInteger: 1] forKey:@"section"];
				}
				else {
					[dic setValue:[NSNumber numberWithInteger: row+1-self.wcCount] forKey:@"row"];
					[dic setValue:[NSNumber numberWithInteger: 0] forKey:@"section"];
				}

			}
			else {
				[dic setValue:[NSNumber numberWithInteger: row] forKey:@"row"];
				[dic setValue:[NSNumber numberWithInteger: 0] forKey:@"section"];
				
			}
*/
			[dic setValue:[NSNumber numberWithBool:YES] forKey:@"isstar"];
			[dic setValue:@"opml" forKey:@"type"];
			[self performSelectorOnMainThread:@selector(updateUI:) withObject:dic waitUntilDone:YES];
			[NSThread sleepForTimeInterval:0.2f];
			OMPLFeed *opf=[[OMPLFeed alloc] init];
			tmpurl=[NSString stringWithFormat:@"%@[%d]/outline",url,row+1];
			tmpcount = [opf getCurarrCountFrom:rootNode usexpath:tmpurl];
			[dic setValue:[NSNumber numberWithInteger: tmpcount] forKey:@"count"];
			[dic setValue:[NSNumber numberWithBool:NO] forKey:@"isstar"];
			[self performSelectorOnMainThread:@selector(updateUI:) withObject:dic waitUntilDone:YES];
			[opf release];
		}
		else if ([tmpvt isEqualToString:@"rss"]) 
		{
			if (self.wcCount!=0 && self.myLoveCount!=0)
			{
				if (row>=self.wcCount+self.myLoveCount)
				{
					[dic setValue:[NSNumber numberWithInteger: row-self.wcCount-self.myLoveCount] forKey:@"row"];
					[dic setValue:[NSNumber numberWithInteger: 2] forKey:@"section"];
				}
				else if (row>=self.myLoveCount && row<self.wcCount+self.myLoveCount) 
				{
					[dic setValue:[NSNumber numberWithInteger: row-self.myLoveCount] forKey:@"row"];
					[dic setValue:[NSNumber numberWithInteger: 1] forKey:@"section"];
				}
				else 
				{
					[dic setValue:[NSNumber numberWithInteger: row] forKey:@"row"];
					[dic setValue:[NSNumber numberWithInteger: 0] forKey:@"section"];	
				}
				
			}
			else if (self.wcCount==0 && self.myLoveCount==0)
			{	
				[dic setValue:[NSNumber numberWithInteger: row] forKey:@"row"];
				[dic setValue:[NSNumber numberWithInteger: 0] forKey:@"section"];
				
			}
			else  if (self.wcCount==0 && self.myLoveCount!=0)
			{
				if (row>=self.myLoveCount)
				{
					[dic setValue:[NSNumber numberWithInteger: row-self.myLoveCount] forKey:@"row"];
					[dic setValue:[NSNumber numberWithInteger: 1] forKey:@"section"];
				}
				else {
					[dic setValue:[NSNumber numberWithInteger: row] forKey:@"row"];
					[dic setValue:[NSNumber numberWithInteger: 0] forKey:@"section"];
				}
			}
			else if (self.wcCount!=0 && self.myLoveCount==0)
			{
				if (row>=self.wcCount)
				{
					[dic setValue:[NSNumber numberWithInteger: row-self.wcCount] forKey:@"row"];
					[dic setValue:[NSNumber numberWithInteger: 1] forKey:@"section"];
				}
				else {
					[dic setValue:[NSNumber numberWithInteger: row] forKey:@"row"];
					[dic setValue:[NSNumber numberWithInteger: 0] forKey:@"section"];
				}
				
			}
			
			//[dic setValue:[NSNumber numberWithInteger: row] forKey:@"row"];
			[dic setValue:[NSNumber numberWithBool:YES] forKey:@"isstar"];
			[dic setValue:@"rss" forKey:@"type"];
			[self performSelectorOnMainThread:@selector(updateUI:) withObject:dic waitUntilDone:YES];
			
			tmpmd5filename=[item objectForKey:@"md5filename"];
			tmprssurl=[item objectForKey:@"xmlurl"];
			RssFeed *rf=[[RssFeed alloc] init];
			[rf parseXMLFileAtURL:tmprssurl cachefile:tmpmd5filename isforce:YES updateRss:[Common getConfig].updateRSSTime];
			OMPLFeed *opf=[[OMPLFeed alloc] init];
			tmpurl=[NSString stringWithFormat:@"%@[%d]",url,row+1];
			[self setrootNode: [opf WriteNotReadRssCount: rf.notreadcount root:rootNode byXpath:tmpurl lastupdate:rf.lastUpdateState]];
			[Common setroot:rootNode];
			[dic setValue:[NSNumber numberWithInteger:rf.lastUpdateState] forKey:@"lastupdate"];
			[dic setValue:[NSNumber numberWithInteger: rf.notreadcount] forKey:@"count"];
			[dic setValue:[NSNumber numberWithBool:NO] forKey:@"isstar"];
			[self performSelectorOnMainThread:@selector(updateUI:) withObject:dic waitUntilDone:YES];
			[opf release];
			//[rf release];
		}
		else if ([tmpvt isEqualToString:@"detail"]) 
		{
			[self performSelectorOnMainThread:@selector(showLoading:) withObject:[NSNumber numberWithBool:YES] waitUntilDone:YES];
			RssFeed *rf=[[RssFeed alloc] init];
			[rf parseXMLFileAtURL:self.rssurl cachefile:self.md5filename isforce:YES updateRss:[Common getConfig].updateRSSTime];
			OMPLFeed *opf=[[OMPLFeed alloc] init];
			[self setrootNode: [opf WriteNotReadRssCount: rf.notreadcount root:rootNode byXpath:url lastupdate:rf.lastUpdateState]];
			[Common setroot:rootNode];
			[self performSelectorOnMainThread:@selector(showLoading:) withObject:[NSNumber numberWithBool:NO] waitUntilDone:YES];
			if (rf.lastUpdateState!=-1) 
			{
			//	NSData *buffer = [NSKeyedArchiver archivedDataWithRootObject: [rf stories]];
			//	self.list = [NSKeyedUnarchiver unarchiveObjectWithData: buffer];
			//	[buffer release];
				
				self.list =[rf stories ];
				[self.tableView reloadData];	
			} 
			else
			{
				UIAlertView *alert=[[UIAlertView alloc]  initWithTitle:@"旺财提示" message:@"网络故障，未能更新,请稍候重试！" delegate:self cancelButtonTitle:@"好" otherButtonTitles:nil];
				[alert  show];
				[alert release];
			}
			//[tmpurl release];
			[item release];
			[dic release];
			//[rf release];
			[opf release];
			break;
		}
		//[tmpurl release];
		[item release];
		[dic release];
	}
	[self.tableView reloadData];
	self.navigationItem.rightBarButtonItem.enabled=YES;
	[pool release];
}
- (IBAction)refresh: (id)sender
{
	[NSThread detachNewThreadSelector:@selector(backrefresh) toTarget:self withObject:nil];
}


- (IBAction)about:(id)sender
{
	UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"旺财阅读 for iphone v0.01" message:nil delegate:nil cancelButtonTitle:@"关闭" otherButtonTitles:nil];
	[alert show];
	[alert release];
}

- (IBAction)add:(id)sender
{

}

-(void) initUITableView
{
	[self.tableView initWithFrame:  CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height-40) 
							style:UITableViewStyleGrouped];
	[self.tableView setSeparatorStyle:UITableViewCellSeparatorStyleSingleLineEtched];
	
}

- (void)viewDidLoad 
{
	if (vType == '\0')
	{
		[self initFirst];
	}
	self.navigationController.delegate=self;
	[self initUITableView];
	[self setIsback:@"NO"];
	if (self.list==nil) {
		[self getOpmlOrRss:NO];
	}
	[self showLoading:NO];
	 self.clearsSelectionOnViewWillAppear = NO;
	[super viewDidLoad];
	//[self.tableView  init ];
	return;
  
}

- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated;
{
	
	if (![[viewController nibName] isEqualToString:@"RssDetailViewController" ])
	{
	//	[self.navigationController con popViewControllerAnimated:YES];
		OPMLViewController *tmp=(OPMLViewController *) viewController ;
		if ([tmp.isback isEqualToString:@"YES"])
		{	
			[tmp setrootNode:[Common getrootE]];
			[tmp getOpmlOrRss:NO];
			[tmp.tableView reloadData];
		}
		[tmp setIsback:@"YES"];
	}
}

#pragma mark -
#pragma mark Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView 
{
	NSLog(@"numberOfSectionsInTableView");
	NSInteger secCount=1;
	if (self.wcCount>0) secCount++;
	if (self.myLoveCount>0) secCount++;
	return secCount;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
	NSLog(@"heightForHeaderInSection");

	if (self.tableView.numberOfSections >1)
	{		
		return 45;
	}
	else {
		return 15;
	}
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
	NSLog(@"heightForFooterInSection");
		if (self.tableView.numberOfSections >1)
		{		
			return 5;
		}
		else {
			return 15;
		}
	
}


- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
	

	if (self.tableView.numberOfSections >1)
	{
		TableHeadController *thead =[[[TableHeadController alloc] init] autorelease];
		if(section == 0)
		{
			if (self.myLoveCount>0) 
				thead.mytitle=@"我的最爱";
			else
			{
				if (self.wcCount>0) 
				{
					thead.mytitle=@"旺财推荐";
				}
				
			}
			
		}
		else if(section==1)
		{
			if (self.myLoveCount>0) {
				thead.mytitle=@"旺财推荐";
			}
			else {
				thead.mytitle= @"分类导航";
			}
		}
		else if (section==2) {
			thead.mytitle= @"分类导航";
		}
		return thead.view;
	}
	else {
		return nil;
	}
	

	
}



- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section==0) 
	{
		if (self.myLoveCount>0) return self.myLoveCount;
		if (self.wcCount>0)  return self.wcCount;
		return [list count]-self.myLoveCount-self.wcCount;
			//retuan [list retain count]
		
	}
	else if (section==1)
	{
		if (self.wcCount>0)  return self.wcCount;
		return [list count]-self.myLoveCount-self.wcCount ;
	}
	else if (section==2)
	{
		return [list count]-self.myLoveCount-self.wcCount;
	}
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
	NSLog(@"heightForRowAtIndexPath");
	if (vType==2)
	{
		return 70;
	}
	else 
	{
		return 50;
	}
}

// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{
	NSLog(@"cellForRowAtIndexPath");
	
    static NSString *CellIdentifier = @"CustomCellIdentifier";
	NSUInteger row = [indexPath row];
	NSInteger section=[indexPath section];
	if (section==1)
	{
		if (self.wcCount==0 || self.myLoveCount==0)
		{
			if (self.wcCount==0) row+=self.myLoveCount;
			if (self.myLoveCount==0) row+=self.wcCount;
		}
		else
		{
			row+=self.myLoveCount;
		}
	}
	else if(section==2)
	{
		row+=self.myLoveCount+self.wcCount;
	}
	NSString *rowString = [[list objectAtIndex:row] objectForKey:@"title"];
	NSString *mytype= [[list objectAtIndex:row] objectForKey:@"vtype"]; 
	NSString *strchild=[[list objectAtIndex:row] objectForKey:@"childcount"];
	NSString *lastupdate=[[list objectAtIndex:row] objectForKey:@"lastupdate"];
	NSString *sublab=[[list objectAtIndex:row] objectForKey:@"sublab"];
	if (![mytype isEqualToString:@"detail"])
	{
		Cell1 *cell = (Cell1 *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
		if (cell == nil) 
		{
			NSArray *nib =[[NSBundle mainBundle] loadNibNamed:@"Cell1" owner:self options:nil ];
			cell =[nib objectAtIndex:0];
		}
		NSString *isad=[[list objectAtIndex:row] objectForKey:@"isad"];
		if ([isad isEqualToString:@"yes"]) {
			[cell.adlabel setHidden:NO];
		}
		else {
			[cell.adlabel setHidden:YES];
		}
		
		cell.nameLabel.text=[Common flattenHTML:rowString];
		if (sublab==nil || [sublab isEqualToString:@""] )
		{
			[cell.nameLabel setFrame:CGRectMake(59, 13, 255, 21)];

		}
		else 
		{
			[cell.nameLabel setFrame:(CGRectMake(59, 8, 255, 21))];
			sublab=[Common flattenHTML:sublab];
			cell.sublabel.text=sublab;
		}
		if ([mytype isEqualToString:@"rss"])
		{
			if (lastupdate==nil || [lastupdate isEqualToString:@"yes"])
			{
				cell.imageView.image =[UIImage imageNamed:@"leftall.png"];
			}
			else 
			{
				cell.imageView.image =[UIImage imageNamed:@"lefered.png"];
			}
			//需要判断是否是mylove
			//[cell.contentView addSubview:[self makeDetailDisclosureButton:YES ]];		
			BOOL ismylove=YES;
			if (ismylove)
			{
				[cell.button setImage:[UIImage imageNamed:@"ismylove"] forState:UIControlStateNormal];
				cell.button.tag=1;
			}
			else {
				[cell.button setImage:[UIImage imageNamed:@"nomylove"] forState:UIControlStateNormal];
				cell.button.tag=0;
			}
			
			[cell.button addTarget: self
					   action: @selector(accessoryButtonTapped:withEvent:)
			 forControlEvents: UIControlEventTouchUpInside];
			
			
			
		}
		else if([mytype isEqualToString:@"opml"]) 
		{
			cell.imageView.image =[UIImage imageNamed:@"leftfang.png"];
			[cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
		    cell.button.hidden=YES;
			//[cell.contentView addSubview:[self makeDetailDisclosureButton:YES opml:YES]];		
		}
		if (strchild==nil || [strchild isEqualToString:@"0"])
		{
			cell.countlabel.text=@"-";
		}
		else 
		{
			cell.countlabel.text=[[list objectAtIndex:row] objectForKey:@"childcount"];
		}
		//[rowString release];
		return cell;
	}
	else 
	{
		Cell2 *cell = (Cell2 *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
		if (cell == nil) 
		{
			NSArray *nib =[[NSBundle mainBundle] loadNibNamed:@"Cell1" owner:self options:nil ];
			cell =[nib objectAtIndex:1];
		}
		cell.titlelab.text=[Common flattenHTML:rowString];
		cell.subtitlelab.text=[[list objectAtIndex:row] objectForKey:@"short"];
		NSString *isread=[[list objectAtIndex:row] objectForKey:@"isread"];
		if ([isread isEqualToString:@"yes"])
		{
			[cell.isreadimg setHidden:YES ];  
		}
		else
		{
			[cell.isreadimg setHidden:NO];
		}
		//[rowString release];
		return cell;
	}
    
}

- (void) accessoryButtonTapped: (UIControl *) button withEvent: (UIEvent *) event
{
    NSIndexPath * indexPath = [self.tableView indexPathForRowAtPoint: [[[event touchesForView: button] anyObject] locationInView: self.tableView]];
    if ( indexPath == nil )
        return;
	
    [self.tableView.delegate tableView: self.tableView accessoryButtonTappedForRowWithIndexPath: indexPath];
}

-(void)backGolist :(OPMLViewController *) tmp
{
	NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
	NSMutableDictionary *dic=[[NSMutableDictionary alloc] init];
	NSInteger row=tmp.currow;
	if (self.wcCount!=0 && self.myLoveCount!=0)
	{
		if (row>=self.wcCount+self.myLoveCount)
		{
			[dic setValue:[NSNumber numberWithInteger: row-self.wcCount-self.myLoveCount] forKey:@"row"];
			[dic setValue:[NSNumber numberWithInteger: 2] forKey:@"section"];
		}
		else if (row>=self.myLoveCount && row<self.wcCount+self.myLoveCount) 
		{
			[dic setValue:[NSNumber numberWithInteger: row-self.myLoveCount] forKey:@"row"];
			[dic setValue:[NSNumber numberWithInteger: 1] forKey:@"section"];
		}
		else 
		{
			[dic setValue:[NSNumber numberWithInteger: row] forKey:@"row"];
			[dic setValue:[NSNumber numberWithInteger: 0] forKey:@"section"];	
		}
		
	}
	else if (self.wcCount==0 && self.myLoveCount==0)
	{	
		[dic setValue:[NSNumber numberWithInteger: row] forKey:@"row"];
		[dic setValue:[NSNumber numberWithInteger: 0] forKey:@"section"];
		
	}
	else  if (self.wcCount==0 && self.myLoveCount!=0)
	{
		if (row>=self.myLoveCount)
		{
			[dic setValue:[NSNumber numberWithInteger: row-self.myLoveCount] forKey:@"row"];
			[dic setValue:[NSNumber numberWithInteger: 1] forKey:@"section"];
		}
		else {
			[dic setValue:[NSNumber numberWithInteger: row] forKey:@"row"];
			[dic setValue:[NSNumber numberWithInteger: 0] forKey:@"section"];
		}
	}
	else if (self.wcCount!=0 && self.myLoveCount==0)
	{
		if (row>=self.wcCount)
		{
			[dic setValue:[NSNumber numberWithInteger: row-self.wcCount] forKey:@"row"];
			[dic setValue:[NSNumber numberWithInteger: 1] forKey:@"section"];
		}
		else {
			[dic setValue:[NSNumber numberWithInteger: row] forKey:@"row"];
			[dic setValue:[NSNumber numberWithInteger: 0] forKey:@"section"];
		}
		
	}
	
	//[dic setValue:[NSNumber numberWithInteger:tmp.currow] forKey:@"row"];
	
	//[dic setValue:[NSNumber numberWithInteger: 0] forKey:@"section"];
	[dic setValue:[NSNumber numberWithBool:YES] forKey:@"isstar"];
	[dic setValue:@"white" forKey:@"color"];
	[dic setValue:@"rss" forKey:@"type"];
	[self performSelectorOnMainThread:@selector(updateUI:) withObject:dic waitUntilDone:NO];	
	[dic setValuesForKeysWithDictionary:[tmp initRssList:tmp isforce:NO]];
	[dic setValue:[NSNumber numberWithBool:NO] forKey:@"isstar"];
	[self performSelectorOnMainThread:@selector(updateUI:) withObject:dic waitUntilDone:NO];	
	
	if ([[dic valueForKey:@"lastupdate"] intValue]==-1) {
		UIAlertView *alert=[[UIAlertView alloc]  initWithTitle:@"旺财提示" message:@"网络故障，未能更新,请稍候重试！" delegate:self cancelButtonTitle:@"好" otherButtonTitles:nil];
		[alert show];
		[alert release];
		
		if (tmp.list!=nil && [tmp.list count]>0)
		{
			[self.list removeAllObjects];
			[self.navigationController  pushViewController:tmp
												  animated:YES];
			[tmp release];
		}
		
	}
	else 
	{
		[self.list removeAllObjects];
		[self.navigationController  pushViewController:tmp
											  animated:YES];
		[tmp release];
	}
	
	
	
//	[self performSelectorOnMainThread:@selector(updateUI:) withObject:dic waitUntilDone:YES];
		[pool release];
}


- (void)getNextId:(NSInteger)row title:(NSString *)str
{
	NSMutableDictionary * item;
 //   NSMutableDictionary *item=[[NSMutableDictionary alloc] initWithDictionary:[self.list objectAtIndex:row] copyItems:YES];
    item=[self.list objectAtIndex:row];
	NSString *tmpvt=[item objectForKey:@"vtype"];
	if ([tmpvt isEqualToString: @"opml"])
	{
		OPMLViewController *tmpo=[[OPMLViewController alloc] init];
		tmpo.title=[item objectForKey:@"title"];
		tmpo.url=[[NSString alloc] initWithFormat:@"%@[%d]/outline",url,row+1];
		[tmpo setVType:1];
		[tmpo setrootNode:rootNode];
		[Common setroot:rootNode];
		[self.list removeAllObjects];
		[self.navigationController  pushViewController:tmpo
											 animated:YES];
				[tmpo release];
		//[item release];
		return;
	}
	if ([tmpvt isEqualToString: @"rss"])
	{
		OPMLViewController *tmp=[[OPMLViewController alloc] init] ;
	
		tmp.md5filename=[item objectForKey:@"md5filename"];
		tmp.title=[item objectForKey:@"title"];
		tmp.rssurl=[item objectForKey:@"xmlurl"];
		tmp.url=[[NSString alloc] initWithFormat:@"%@[%d]",url,row+1];
		tmp.currow=row;
		tmp.vType=2;
		[tmp setrootNode:rootNode];
		[Common setroot:rootNode];
		[NSThread detachNewThreadSelector:@selector(backGolist:) toTarget:self withObject:tmp];
		//[tmp release];
		//[item release];
		
		
		return;
	}
		
	if ([tmpvt isEqualToString: @"detail"])
	{
		
		RssDetailViewController *tmpr=[[[RssDetailViewController alloc] initWithNibName:@"RssDetailViewController" bundle:nil] autorelease];
		//[tmp ]
		tmpr.row=row;
		tmpr.mytitle=self.title;
		tmpr.list=[[NSMutableArray  arrayWithArray:self.list] retain];
		
		[Common setroot:rootNode];
		//[self.list removeAllObjects];
		
		[self.navigationController  pushViewController:tmpr
											  animated:YES];
			return;
	}
		
}

- (void)tableView:(UITableView *)tableView 
didSelectRowAtIndexPath:(NSIndexPath *)indexPath 
{
	NSUInteger row = [indexPath row];
	NSInteger section=[indexPath section];
	if (section==1)
	{
		if (self.wcCount==0 || self.myLoveCount==0)
		{
			if (self.wcCount==0) row+=self.myLoveCount;
			if (self.myLoveCount==0) row+=self.wcCount;
		}
		else
		{
			row+=self.myLoveCount;
		}
	}
	else if(section==2)
	{
		row+=self.myLoveCount+self.wcCount;
	}
	
	[self getNextId:row title:nil];
}

- (void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath;
{
	
	//NSUInteger row = [indexPath row];
	
	Cell1 *cell =(Cell1 *)[self.tableView cellForRowAtIndexPath:indexPath];
	NSString *mes;
	if (cell.button.tag==1)
	{
		[cell.button setImage:[UIImage imageNamed:@"nomylove.png"] forState:UIControlStateNormal];
		mes=@"已取消加入我的最爱";
		cell.button.tag=0;
	}
	else {
		
		[cell.button setImage:[UIImage imageNamed:@"ismylove.png"] forState:UIControlStateNormal];
		mes=@"已加入我的最爱";
		cell.button.tag=1;
	}
	UIAlertView *alert=[[UIAlertView alloc]  initWithTitle:@"旺财提示" message:mes delegate:self cancelButtonTitle:@"好" otherButtonTitles:nil];
	[alert  show];
	[alert release];

	
	//[self getNextId:row title:nil];
}
/*
-(UIButton *) makeDetailDisclosureButton: (BOOL)ismylove ompl: (BOOL)isompl
{
	
	UIButton * button= [[[UIButton alloc]init]autorelease];
	CGRect buttonf = CGRectMake(271 , 13 , 20, 20);
	button.frame = buttonf;
	if (!isompl)
	{
		button= [UIButton buttonWithType:UIButtonTypeCustom];
		
		if (ismylove)
		{
			[button setBackgroundImage:[UIImage imageNamed:@"ismylove.png"] forState:UIControlStateNormal];
			
		}
		else {
			[button setBackgroundImage:[UIImage imageNamed:@"ismylove.png"] forState:UIControlStateNormal];
			
		}
		[button addTarget: self
				   action: @selector(accessoryButtonTapped:withEvent:)
		 forControlEvents: UIControlEventTouchUpInside];
	}
	else {
		
		button= [UIButton buttonWithType:UITableViewCellAccessoryDisclosureIndicator];
	}
	
    return ( button );
}
*/

-(UIButton *) makeDetailDisclosureButton: (BOOL)ismylove 
{
	
	UIButton * button= [[[UIButton alloc]init]autorelease];
	CGRect buttonf = CGRectMake(271 , 13 , 20, 20);
	button.tag=13;
	
			
		button= [UIButton buttonWithType:UIButtonTypeCustom];
		button.frame = buttonf;

	if (ismylove)
	{
		[button setImage:[UIImage imageNamed:@"ismylove"] forState:UIControlStateNormal];

	}
	else {
		[button setImage:[UIImage imageNamed:@"nomylove"] forState:UIControlStateNormal];
	}

	[button addTarget: self
               action: @selector(accessoryButtonTapped:withEvent:)
     forControlEvents: UIControlEventTouchUpInside];

    
	
		return ( button );
}
#pragma mark -
#pragma mark Memory management


- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Relinquish ownership any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
	NSLog(@"fuckunload");
	// Relinquish ownership of anything that can be recreated in viewDidLoad or on demand.
    // For example: self.myOutlet = nil;
}


- (void)dealloc 
{   
	[list release];
	[url release];
	[md5filename release];
	[rssurl release];
	[isback release];		
	//[super dealloc];
}
 


@end

